package com.jy.task.fileoper;

import java.sql.Timestamp;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;

import com.jy.common.utils.SpringWebContextUtil;
import com.jy.common.utils.base.UuidUtil;
import com.jy.entity.filemanager.TSFile;
import com.jy.entity.filemanager.TSHitask;
import com.jy.entity.filemanager.TSProduct;
import com.jy.entity.filemanager.TSTaske;
import com.jy.entity.filemanager.TSUser;
import com.jy.service.filemanager.histask.HisTaskService;
import com.jy.service.filemanager.product.ProductService;
import com.jy.service.filemanager.taskmain.TaskMainService;
import com.jy.service.filemanager.user.TuserService;
import com.jy.task.utils.ScheduleTaskUtils;

/* 案例 同步和不同步的区别  非同步需要加@DisallowConcurrentExecution */
public class FileTask implements Job {

	private static final Logger LOG = LoggerFactory.getLogger(FileTask.class);
	private static boolean isRun = false;

	@Override
	public void execute(JobExecutionContext context) {
		ApplicationContext ac = SpringWebContextUtil.getApplicationContext();
		HisTaskService hisTaskService = (HisTaskService) ac
				.getBean("hisTaskService");
		TaskMainService serviceTask = (TaskMainService) ac
				.getBean("mainTaskService");
		TSTaske scheduleJob = (TSTaske) context.getMergedJobDataMap().get(
				ScheduleTaskUtils.JOB_PARAM_KEY);
		scheduleJob = serviceTask.findTaskById(scheduleJob);
		ProductService serviceProduct = (ProductService) ac
				.getBean("productService");
		TuserService serviceuser = (TuserService) ac.getBean("tUserService");
		// 任务为启动 共享文件连接 tcp连接
		Date updateDate = new Timestamp(System.currentTimeMillis());
		TSHitask hitask = new TSHitask();
		try {
			// System.out.println("???" + scheduleJob.getStatus());
			if (scheduleJob.getStatus() != 5) {
				if (scheduleJob != null) {
					updateTakeStatus(5, scheduleJob, updateDate, 3);
					hitask.setId(UuidUtil.get32UUID());
					hitask.setTaskCode(scheduleJob.getTaskCode());
					hitask.setProjectId(scheduleJob.getProjectId());
					TSUser user = serviceuser.findUserById(scheduleJob
							.getAimsIds());
					TSProduct product = serviceProduct
							.getProductById(scheduleJob.getSourceId());
					hitask.setPushType(user.getPushType());
					hitask.setStartDate(new Timestamp(System
							.currentTimeMillis()));
					Date startDate = scheduleJob.getNewDate() != null ? scheduleJob
							.getNewDate() : scheduleJob.getStartDate();
					if (scheduleJob.getUpdateType() == 2) {
						startDate = scheduleJob.getStartDate();
					}

					Integer judgeClient = judgeClientType(product);
					// 判断源是否能连接 若不能连接则任务异常处理
					// 0未能连接 1 smb1连接 2.smb2连接
					if (judgeClient != 0) {
						// 共享文件夹
						if (user.getPushType() != null
								&& user.getPushType() == 1) {
							if (judgeClient == 1) {
								smb1tosmb1(product, user, startDate,
										scheduleJob, hitask, updateDate);
							} else if (judgeClient == 2) {
								smb2tosmb2(product, user, startDate,
										scheduleJob, hitask, updateDate);
							}
						} else {
							if (judgeClient == 1) {
								smb1toTcp(product, user, startDate,
										scheduleJob, hitask, updateDate);
							} else if (judgeClient == 2) {
								smb2toTcp(product, user, startDate,
										scheduleJob, hitask, updateDate);
							}
						}

					} else {
						// 源不能连接
						hitask.setProblemType(1);
						saveHisForError(hitask);
						updateTakeStatus(1, scheduleJob, updateDate, 1);
					}
				}
			}
		} catch (Exception e) {
			updateTakeStatus(1, scheduleJob, updateDate, 1);
			hitask.setEndDate(new Timestamp(System.currentTimeMillis()));
			hitask.setFileNum(0);
			hitask.setProblemType(1);
			hitask.setCreateDate(new Timestamp(System.currentTimeMillis()));
			hisTaskService.insert(hitask);
			e.printStackTrace();
		} finally {
			updateTakeStatus(1, scheduleJob, updateDate, 3);
		}

	}

	// 判断源类型
	private Integer judgeClientType(TSProduct product) {
		String remoteUrl = "smb://" + product.getUserName() + ":"
				+ product.getPassword() + "@" + product.getSourceAddress() + "";
		if (!remoteUrl.substring(remoteUrl.length() - 1).equals("/")) {
			remoteUrl += "/";
		}
		SmbOper smbOper = new SmbOper(product.getSourceAddress(),
				product.getUserName(), product.getPassword(), "");
		// "smb://administrator:CloudBim_403@192.168.0.13/test/name/",
		boolean resultSmbConnct = smbOper.tcpConnect();
		if (resultSmbConnct)
			return 1;

		else {
			String ip = getNewFileIp(product.getSourceAddress(), 1);
			String fileNameStr = getNewFileIp(product.getSourceAddress(), 2);
			Smb2Oper smbOper2 = new Smb2Oper(ip, product.getUserName(),
					product.getPassword(), fileNameStr);
			boolean resultSmbConnct2 = smbOper2.smb2Connect();
			if (resultSmbConnct2)
				return 2;
		}

		return 0;

	}

	// 判断目的类型
	private Integer judgeserverType(TSUser userStr) {
		String remoteUrl = "smb://" + userStr.getServerName() + ":"
				+ userStr.getServerPassword() + "@" + userStr.getAddress() + "";
		if (!remoteUrl.substring(remoteUrl.length() - 1).equals("/")) {
			remoteUrl += "/";
		}
		SmbOper smbOper = new SmbOper(userStr.getAddress(),
				userStr.getServerName(), userStr.getServerPassword(), "");
		// "smb://administrator:CloudBim_403@192.168.0.13/test/name/",
		boolean resultSmbConnct = smbOper.tcpConnect();
		if (resultSmbConnct)
			return 1;
		else {
			String ip = getNewFileIp(userStr.getAddress(), 1);
			String fileNameStr = getNewFileIp(userStr.getAddress(), 2);
			Smb2Oper smbOper2 = new Smb2Oper(ip, userStr.getServerName(),
					userStr.getServerPassword(), fileNameStr);
			boolean resultSmbConnct2 = smbOper2.smb2Connect();
			if (resultSmbConnct2)
				return 2;
		}
		return 0;
	}

	private void smb1tosmb1(TSProduct product, TSUser user, Date startDate,
			TSTaske scheduleJob, TSHitask hitask, Date updateDate) {
		Integer connectTye = judgeserverType(user);
		// 目的能连接
		if (connectTye != 0) {
			String remoteUrl = "smb://" + product.getUserName() + ":"
					+ product.getPassword() + "@" + product.getSourceAddress()
					+ "";
			if (!remoteUrl.substring(remoteUrl.length() - 1).equals("/")) {
				remoteUrl += "/";
			}
			String localDir = "smb://" + user.getServerName() + ":"
					+ user.getServerPassword() + "@" + user.getAddress() + "";
			SMB1Connect smbConnect = new SMB1Connect(remoteUrl, localDir,
					product.getFileName(), product.getExtenName(), startDate,
					scheduleJob.getIsSubFile());
			if (connectTye == 1) {
				// 共享文件夹对共享文件夹传文件
				boolean resultFlag = smbConnect.smbTosmbMother();
				if (!resultFlag) {
					hitask.setProblemType(2);
					saveHisForError(hitask);
					updateTakeStatus(1, scheduleJob, updateDate, 2);
				} else {
					List<TSFile> listFile = smbConnect.getresultFIle();
					smbTosmb(hitask, listFile, scheduleJob,
							smbConnect.getNewDate());
					updateTakeStatus(1, scheduleJob, updateDate, 0);
				}
			} else if (connectTye == 2) {
				boolean resultFlag = smbConnect.smbTosmb2Month(
						getNewFileIp(user.getAddress(), 1),
						user.getServerName(), user.getServerPassword(),
						getNewFileIp(user.getAddress(), 2),
						getNewFileIp(user.getAddress(), 3));
				List<TSFile> listFile = smbConnect.getresultFIle();
				smbTosmb(hitask, listFile, scheduleJob, smbConnect.getNewDate());
				updateTakeStatus(1, scheduleJob, updateDate, 0);
			}
		} else {
			// 目的不能连接
			hitask.setProblemType(2);
			saveHisForError(hitask);
			updateTakeStatus(1, scheduleJob, updateDate, 2);
		}

	}

	private void smb2tosmb2(TSProduct product, TSUser user, Date startDate,
			TSTaske scheduleJob, TSHitask hitask, Date updateDate) {

		String ipUser = getNewFileIp(user.getAddress(), 1);
		String fileNameStrUser = getNewFileIp(user.getAddress(), 2);
		Smb2Oper smbOperUser = new Smb2Oper(ipUser, user.getServerName(),
				user.getServerPassword(), fileNameStrUser);
		boolean resultSmbConnctSour = smbOperUser.smb2Connect();
		// 目的能连接
		if (resultSmbConnctSour) {
			// 共享文件夹对共享文件夹传文件
			String ip = getNewFileIp(product.getSourceAddress(), 1);
			String fileNameStr = getNewFileIp(product.getSourceAddress(), 2);
			SMB2Connect smbConnect = new SMB2Connect(ip, product.getUserName(),
					product.getPassword(), fileNameStr, product.getFileName(),
					startDate, scheduleJob.getIsSubFile());
			boolean resultFlag = smbConnect.smbTosmbMother(
					getNewFileIp(product.getSourceAddress(), 3),
					getNewFileIp(user.getAddress(), 3), ipUser,
					user.getServerName(), user.getServerPassword(),
					getNewFileIp(user.getAddress(), 2));
			if (!resultFlag) {
				hitask.setProblemType(2);
				saveHisForError(hitask);
				updateTakeStatus(1, scheduleJob, updateDate, 2);
			} else {
				List<TSFile> listFile = smbConnect.getresultFIle();
				smbTosmb(hitask, listFile, scheduleJob, smbConnect.getNewDate());
				updateTakeStatus(1, scheduleJob, updateDate, 0);
			}
		} else {
			// 目的不能连接
			hitask.setProblemType(2);
			saveHisForError(hitask);
			updateTakeStatus(1, scheduleJob, updateDate, 2);
		}
	}

	private void smb1toTcp(TSProduct product, TSUser user, Date startDate,
			TSTaske scheduleJob, TSHitask hitask, Date updateDate) {
		// tcp连接
		String remoteUrl = "smb://" + product.getUserName() + ":"
				+ product.getPassword() + "@" + product.getSourceAddress() + "";
		if (!remoteUrl.substring(remoteUrl.length() - 1).equals("/")) {
			remoteUrl += "/";
		}
		String newUrlStr = user.getAddress();
		if (user.getAddress().indexOf("/") > 0) {
			newUrlStr = user.getAddress().substring(0,
					user.getAddress().indexOf("/"));
		}
		String loacalDir = "/";
		if (user.getAddress().indexOf("/") > 0) {
			loacalDir = user.getAddress().substring(
					user.getAddress().indexOf("/"));
		}
		TcpClient tcpOper = new TcpClient(remoteUrl, loacalDir,
				product.getFileName(), product.getExtenName(), startDate,
				scheduleJob.getIsSubFile(), loacalDir, newUrlStr,
				user.getPort(), user.getServerName(), user.getServerPassword());
		try {
			if (tcpOper.connect()) {
				Map<String, Object> neMap = tcpOper.smbTosmbMother();
				if ((Boolean) neMap.get("Msg")) {
					List<TSFile> listFile = tcpOper.getFileList();
					System.out.println(">>>guanblianjie" + listFile);
					smbTosmb(hitask, listFile, scheduleJob,
							tcpOper.getNewDate());
					updateTakeStatus(1, scheduleJob, updateDate, 0);
				} else {
					hitask.setProblemType(2);
					saveHisForError(hitask);
					updateTakeStatus(1, scheduleJob, updateDate, 2);
				}

				// tcpOper.closeFtp();
			} else {
				// 目的不能连接
				hitask.setProblemType(2);
				saveHisForError(hitask);
				updateTakeStatus(1, scheduleJob, updateDate, 2);
				tcpOper.closeFtp();
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	private void smb2toTcp(TSProduct product, TSUser user, Date startDate,
			TSTaske scheduleJob, TSHitask hitask, Date updateDate) {
		// tcp连接
		// 处理url
		String ip = getNewFileIp(product.getSourceAddress(), 1);
		String fileNameStr = getNewFileIp(product.getSourceAddress(), 2);
		String newUrlStr = user.getAddress();
		if (user.getAddress().indexOf("/") > 0) {
			newUrlStr = user.getAddress().substring(0,
					user.getAddress().indexOf("/"));
		}
		String loacalDir = "/";
		if (user.getAddress().indexOf("/") > 0) {
			loacalDir = user.getAddress().substring(
					user.getAddress().indexOf("/"));
		}
		TcpClient2 tcpOper = new TcpClient2(product.getFileName(),
				product.getExtenName(), startDate, scheduleJob.getIsSubFile(),
				loacalDir, newUrlStr, user.getPort(), user.getServerName(),
				user.getServerPassword());
		try {
			if (tcpOper.connect()) {

				if (tcpOper.smb2Connect(ip, product.getUserName(),
						product.getPassword(), fileNameStr)) {
					Map<String, Object> neMap = tcpOper.smbToftp(
							getNewFileIp(product.getSourceAddress(), 3),
							loacalDir);
					if ((Boolean) neMap.get("Msg")) {
						List<TSFile> listFile = tcpOper.getFileList();
						System.out.println(">>>guanblianjie" + listFile);
						smbTosmb(hitask, listFile, scheduleJob,
								tcpOper.getNewDate());
						updateTakeStatus(1, scheduleJob, updateDate, 0);
					} else {
						hitask.setProblemType(2);
						saveHisForError(hitask);
						updateTakeStatus(1, scheduleJob, updateDate, 2);
					}
				}
			} else {
				// 目的不能连接
				hitask.setProblemType(2);
				saveHisForError(hitask);
				updateTakeStatus(1, scheduleJob, updateDate, 2);
				tcpOper.closeFtp();
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	// 保存历史表
	public static void smbTosmb(TSHitask hitask, List<TSFile> listFile,
			TSTaske scheduleJob, Date newDate) {
		ApplicationContext ac = SpringWebContextUtil.getApplicationContext();
		HisTaskService hisTaskService = (HisTaskService) ac
				.getBean("hisTaskService");
		TaskMainService serviceTask = (TaskMainService) ac
				.getBean("mainTaskService");
		// 保存历史表
		hitask.setEndDate(new Date());
		hitask.setFileNum(listFile.size());
		hitask.setProblemType(0);
		hitask.setCreateDate(new Timestamp(System.currentTimeMillis()));
		hisTaskService.insert(hitask);
		// 保存文件
		for (TSFile obj : listFile) {
			obj.setHitaskId(hitask.getId());
			obj.setCreateDate(new Timestamp(System.currentTimeMillis()));
			hisTaskService.saveTaskFile(obj);
		}
		// 修改任务最新操作时间

		if (newDate != null && listFile.size() > 0) {
			scheduleJob.setNewDate(newDate);
		}

		scheduleJob.setFileNum(listFile.size());
		serviceTask.updateNewDate(scheduleJob);
	}

	private void updateTakeStatus(Integer status, TSTaske taskTask,
			Date updateDate, Integer problemType) {
		ApplicationContext ac = SpringWebContextUtil.getApplicationContext();
		TaskMainService serviceTask = (TaskMainService) ac
				.getBean("mainTaskService");
		TSTaske objTaske = taskTask;
		objTaske.setStatus(status);
		objTaske.setUpdateDate(updateDate);
		if (problemType == 3) {
			// objTaske.setProblemType(taskTask.getProblemType());
			serviceTask.updateOnlyStatus(objTaske);
		} else {
			objTaske.setProblemType(problemType.toString());
			serviceTask.updateNewStatus(objTaske);
		}

	}

	private void saveHisForError(TSHitask hisTask) {
		ApplicationContext ac = SpringWebContextUtil.getApplicationContext();
		HisTaskService hisTaskService = (HisTaskService) ac
				.getBean("hisTaskService");
		hisTask.setCreateDate(new Timestamp(System.currentTimeMillis()));
		hisTask.setEndDate(new Date());
		hisTask.setFileNum(0);
		hisTaskService.insert(hisTask);
	}

	// type=1 ip =2大文件夹 3 最终文件夹
	private String getNewFileIp(String path, Integer type) {
		String str = "";
		if (path.length() > 0) {
			String[] strPath = path.split("/");
			if (type == 1) {
				str = strPath[0];
			}
			if (type == 2) {
				if (strPath.length > 1) {
					str = strPath[1];
				}
			}
			if (type == 3) {
				if (strPath.length > 2) {
					str = path.substring(path.indexOf(strPath[2])) + "/";
					str = str.replace("//", "/");
				}
			}
		}
		return str;
	}
}
